const Koa = require('koa')
const Router = require('koa-router')
const views = require('koa-views')
const static = require('koa-static')
const koaBody = require('koa-body')
const fs = require('fs')

let app = new Koa()
let router = new Router()
app.use(koaBody({
    multipart: true
}))
app.use(views(__dirname + '/views'))
app.use(views(__dirname + '/views'))

router.get('/index', async ctx => {
    await ctx.render('index.html')
})
router.get('/addNews', async ctx => {
    await ctx.render('addNews.html')

})
router.post('/postfile', ctx => {
    ctx.body = ctx.request.files.myimg.originalFilename
    ctx.body = ctx.request.body
    let obj = ctx.request.body
    //console.log(obj);    
    let tempath = ctx.request.files.myimg.filepath
    let orgName = ctx.request.files.myimg.originalFilename;
    obj.imgsrc = 'files' + orgName
    let jsonObj = JSON.stringify(obj)
    console.log(jsonObj);


    if (!fs.existsSync('./static/files')) {
        fs.mkdirSync('./static/files')
    }
    fs.copyFileSync(tempath, './static/files' + orgName)
    if (!fs.existsSync('./static/data')) {
        fs.mkdirSync('./static/data')
    }
    fs.writeFileSync('./static/data/data.json',jsonObj)

})
app.use(router.routes())
app.listen(8989)